package com.example.day04_1_zuul.filter;

import com.netflix.zuul.IZuulFilter;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.http.HttpStatus;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Component
public class LoginFilter extends ZuulFilter {
    @Override
    //是否执行当前过滤器
    public boolean shouldFilter() {
        return true;
    }

    @Override
    //过滤器业务逻辑代码
    public Object run() throws ZuulException {
        //判断是否登录：
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        //请求参数有username，就代表登录
        String username = request.getParameter("username");
        if(username==null || "".equals(username)){
            //未登录
            try {
                requestContext.getResponse().getWriter().write("未登录");
            } catch (IOException e) {
                e.printStackTrace();
            }
            //过滤器不往下执行
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseStatusCode(HttpStatus.SC_UNAUTHORIZED);
        }

        return null;
    }

    @Override
    //过滤器类型： pre routing post error
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    //过滤器执行的顺序，数字越小越优先
    public int filterOrder() {
        return FilterConstants.PRE_DECORATION_FILTER_ORDER-1;
    }
}
